<template>
  <NavBar></NavBar>
  <ContentFiled>
    <table class="table table-striped table-hover" style="text-align: center">
      <thead>
        <tr>
          <th>黑</th>
          <th>白</th>
          <th>对战结果</th>
          <th>对战时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="record in records" :key="record.recordId">
          <td>
            <img :src="record.avatarUrl1" alt="" class="record-user-photo" />
            &nbsp;
            <span class="record-user-username">{{ record.username1 }}</span>
          </td>
          <td>
            <img :src="record.avatarUrl2" alt="" class="record-user-photo" />
            &nbsp;
            <span class="record-user-username">{{ record.username2 }}</span>
          </td>
          <td>
            {{
              record.winner === 0
                ? "平局"
                : record.winner === 1
                ? "白胜"
                : "黑胜"
            }}
          </td>
          <td>{{ record.gameOverTime }}</td>
          <td>
            <button
              @click="open_record_content(record.recordId)"
              type="button"
              class="btn btn-info"
            >
              查看回放
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <nav aria-label="...">
      <ul class="pagination" style="float: right">
        <li class="page-item" @click="click_page(-2)">
          <a class="page-link" href="#">上一页</a>
        </li>
        <li
          v-for="page in pages"
          :key="page.number"
          :class="'page-item ' + page.is_active"
          @click="click_page(page.number)"
        >
          <a class="page-link" href="#">{{ page.number }}</a>
        </li>
        <li class="page-item" @click="click_page(-1)">
          <a class="page-link" href="#">下一页</a>
        </li>
      </ul>
    </nav>
  </ContentFiled>
</template>

<script>
import ContentFiled from "@/components/ContentFiled.vue";
import { useStore } from "vuex";
import $ from "jquery";
import { ref } from "vue";
import NavBar from "@/components/NavBar.vue";
import router from "@/router";

export default {
  components: {
    NavBar,
    ContentFiled,
  },

  setup() {
    const store = useStore();
    let records = ref([]);
    let current_page = 1;
    let total_records = 0;
    let pages = ref([]);
    let size = 10;

    const click_page = (page) => {
      if (page === -2) page = current_page - 1;
      else if (page === -1) page = current_page + 1;

      let max_pages = Math.ceil(total_records / size);

      if (page >= 1 && page <= max_pages) {
        pull_page(page);
      }
    };

    const update_pages = () => {
      let max_pages = Math.ceil(total_records / size);
      let new_pages = [];
      for (let i = current_page - 2; i <= current_page + 2; i++) {
        if (i >= 1 && i <= max_pages) {
          new_pages.push({
            number: i,
            is_active: i === current_page ? "active" : "",
          });
        }
      }
      pages.value = new_pages;
    };

    const pull_page = (page) => {
      current_page = page;
      console.log("用户id点1", store.state.user.id);
      $.ajax({
        url: "http://localhost:7090/api/records/page",
        type: "POST",
        contentType: "application/json",
        headers: {
          Authorization: "Bearer " + store.state.user.token,
        },
        data: JSON.stringify({
          userId: store.state.user.userId,
          page: current_page,
          size: size, // 每页记录数
        }),
        success(resp) {
          records.value = resp.data.data; // 更新为新的数据结构
          total_records = resp.data.total; // 更新总记录数
          update_pages();
        },
        error(resp) {
          console.log(resp);
        },
      });
    };

    pull_page(current_page);

    ///下面是对局数据解析
    function convertToCoordinates(moves) {
      // 使用正则表达式匹配有效的数字
      const validMoves = moves.match(/-?\d+/g);
      // 如果没有有效的数字，返回空数组
      if (!validMoves) {
        return [];
      }
      // 将有效数字转换为数组并映射为数字类型
      const numbers = validMoves.map(Number);
      // 创建一个空数组来存储坐标
      const steps = [];
      // 遍历数字数组，每两个数字组成一个坐标
      for (let i = 0; i < numbers.length; i += 2) {
        steps.push([numbers[i], numbers[i + 1]]);
      }
      return steps;
    }

    const open_record_content = (recordId) => {
      for (const record of records.value) {
        if (record.recordId === recordId) {
          console.log(record);
          store.commit("updateSteps", convertToCoordinates(record.moves));
          store.commit("updateIsRecord", true);
          store.commit("updateRecordUserInfo", {
            user1Name: record.username1,
            user2Name: record.username2,
            user1Photo: record.avatarUrl1,
            user2Photo: record.avatarUrl2,
            user1Id: record.userId1,
            user2Id: record.userId2,
          });
          router.push({ name: "record_content" });

          // store.commit("updateIsRecord",true);
          // store.commit("updateGame",{
          //   map: stringTo2D(record.record.map),
          //   a_id: record.record.aid,
          //   a_sx: 30-2,
          //   a_sy: 1,
          //   b_id: record.record.b_id,
          //   b_sx: 1,
          //   b_sy: 31-2,
          // });
          // store.commit("updateFood",{
          //   food_x: foodTo2D(record.record.foodX),
          //   food_y: foodTo2D(record.record.foodY),
          // });
          // store.commit("updateSteps",{
          //   a_step: record.record.asteps,
          //   b_step: record.record.bsteps,
          // })
          //
          // router.push({
          //   name: "record_content",
          //   params: {
          //     recordId
          //   }
          // })
          //
          // break;
        }
      }
    };

    return {
      records,
      open_record_content,
      pages,
      click_page,
    };
  },
};
</script>

<style scoped>
img.record-user-photo {
  width: 5vh;
  height: 5vh;
  border-radius: 50%;
}
</style>
